package ru.len.cafe.ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ru.len.cafe.entity.model.CafeTable;
import ru.len.cafe.entity.model.Employe;

/**
 * 
 * @author Stanislav Chetvertkov
 *
 */

@Stateless
public class EmployeDao{
 
    @PersistenceContext(unitName="LenCafePU")
    private EntityManager em;
    
    /* Constructor */
    public EmployeDao(){
    }

    /* Methods */
    
    /**
     * Adds Employe to the database
     */
    public void createEmploye(Employe employe){
	em.persist(employe);
    }
    
    /**
     * Deletes Employe form database
     * @param employe
     */
    public void deleteEmploye(Employe employe){
	em.remove(employe);
    }
    
    /**
     * Updates existing Employe in the database
     * @param employe
     */
    public void updateEmploye(Employe employe){
	em.refresh(employe);
    }
    
    /**
     * Finds Employe by ID
     * @param empId
     * @return
     */
    public Employe findEmploye(int empId){
	return ((Employe) em.find(Employe.class, empId));
    }
    
    /**
     * Method queries employees matching for phone number 
     * @param phone
     * @return
     */
    public List<Employe> findEmployeByPhone(String phone){
	String queryString = 
	    "SELECT i from Employe i WHERE i.phone LIKE :pattern ESCAPE :esc";
		
	Query query = em.createQuery(queryString);
	query.setParameter("pattern", "%" + phone + "%");
	query.setParameter("esc", "\\\\");
	
	List<Employe> employees =(List<Employe>) query.getResultList();
	return employees;	
    }
    
    /**
     * Finds Employe by Login
     * @param login
     * @return
     */
    public Employe findEmployeByLogin(String login){
	String queryString = 
	    "SELECT i from Employe i WHERE i.login LIKE :pattern ESCAPE :esc";
		
	Query query = em.createQuery(queryString);
	query.setParameter("pattern", "%" + login + "%");
	query.setParameter("esc", "\\\\");
	
	Employe employe = (Employe) query.getSingleResult();
	return employe;
    }
    
}
